<template>
  <div class="index">
    <van-nav-bar :fixed="true" left-arrow @click-right="onClickRight">
      <template #left>
        <span>聊天({{chatList.length}})</span>
      </template>
      <template #right>
        <van-icon name="search" size="18" color="#000000" />
      </template>
    </van-nav-bar>

    <div class="content">
      <van-swipe-cell v-for="(user,index) in chatList" :key="index">
        <div @click="toChat(user.friendId)" class="user-list van-hairline--bottom">
          <van-row>
            <van-col span="4">
              <div class="user-img">
                <van-image
                  width="40px"
                  height="40px"
                  fit="fill"
                  radius="5"
                  :src="user.friendUserImg"
                />
                <div class="img-num" v-if="user.count > 0">{{user.count > 99 ? '99+' : user.count }}</div>
              </div>
            </van-col>
            <van-col span="16">
              <van-row class="user-content">
                <van-col span="24">{{user.friendUserName}}</van-col>
                <van-col span="24">
                  <div class="van-ellipsis user-msg">{{user.lastMsg}}</div>
                </van-col>
              </van-row>
            </van-col>
            <van-col span="4">
              <span class="time">{{timestampToTime(user.lastMsgTime)}}</span>
            </van-col>
          </van-row>
        </div>
        <template #right>
          <van-button
            size="small"
            @click="deleteChat(user.friendId)"
            round
            text="删除"
            type="danger"
            class="delete-button"
          />
        </template>
      </van-swipe-cell>
    </div>

    <Menu />
  </div>
</template>

<script>
import Menu from "../components/Menu";
import { mapState, mapActions, mapMutations } from "vuex";

export default {
  name: "Index",
  components: {
    Menu
  },
  data() {
    return {
      num: 20
    };
  },
  methods: {
    ...mapActions(["asyncSaveChatList"]),
    ...mapMutations(["updateWsIsLive"]),
    onClickRight() {
      this.$router.push("/friend");
    },
    timestampToTime(timestamp) {
      let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear();
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      let D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let h = date.getHours();
      let m =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();

      //当前时间
      let nowDate = new Date();
      let nowDateYear = nowDate.getFullYear();
      let nowDateMonth =
        nowDate.getMonth() + 1 < 10
          ? "0" + (nowDate.getMonth() + 1)
          : nowDate.getMonth() + 1;
      let nowDateDay =
        nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();

      if (nowDateYear > Y) {
        //大于一年
        return Y + "年" + M + "月" + D + "日";
      } else if (nowDateMonth > M) {
        //小于一年
        return M + "月" + D + "日";
      } else if (nowDateDay > D) {
        if (nowDateDay - D >= 7) {
          return parseInt((nowDateDay - D) / 7) + "周前";
        } else {
          return nowDateDay - D + "天前";
        }
      } else {
        return h + ":" + m;
      }
    },
    //进入聊天页面
    toChat(friendId) {
      //将所有未读消息，变为已读
      let chatList = this.chatList;
      chatList.forEach(element => {
        if (element.friendId == friendId) {
          element.count = 0;
          element.msgList.forEach(item => {
            item.read = true;
          });
        }
      });
      this.asyncSaveChatList(chatList);

      this.$router.push({ path: "/chat", query: { userId: friendId } });
    },
    //删除聊天
    deleteChat(friendId) {
      console.log(friendId);
      this.$dialog
        .confirm({
          message: "删除后，将清空该聊天的消息记录",
          showCancelButton: true,
          confirmButtonText: "删除",
          confirmButtonColor: "#ee0a24"
        })
        .then(() => {
          let chatList = this.chatList;
          chatList.forEach((element, index) => {
            if (element.friendId == friendId) {
              chatList.splice(index, 1);
            }
          });
          this.asyncSaveChatList(chatList);
        })
        .catch(() => {});
    }
  },
  computed: {
    ...mapState(["chatList", "wsIsLive", "user", "token"])
  },
  created() {
    const that = this;
    if (this.token.length > 0) {
      if (!this.wsIsLive && this.user.userId != null) {
        var ws = new WebSocket(this.server.WS + "/" + this.token);
        ws.onopen = function() {
          // WebSocket 已连接上，使用 send() 方法发送数据
          if (ws.readyState == 1) {
            that.updateWsIsLive(true);
          }
        };

        ws.onmessage = function(evt) {
          let data = JSON.parse(evt.data);
          console.log(data);
        };
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.index {
  .content {
    margin-top: 46px;
    margin-bottom: 50px;
    padding-top: 1px;
    padding-bottom: 10px;

    .clearfix::before,
    .clearfix::after {
      content: "";
      display: table;
      clear: both;
    }

    .user-list {
      width: 100%;
      margin-top: 10px;
      padding-bottom: 10px;

      .user-img {
        width: 40px;
        height: 40px;
        border-radius: 5px;
        margin: auto;

        .img-num {
          position: relative;
          top: -48px;
          right: -31px;
          width: 18px;
          height: 18px;
          background-color: red;
          font-size: 12px;
          color: white;
          text-align: center;
          border-radius: 18px;
          line-height: 18px;
        }
      }

      .user-content {
        margin-left: 10px;

        .user-msg {
          font-size: 12px;
          margin-top: 5px;
          margin-bottom: 2px;
          color: #96989a;
        }
      }

      .time {
        font-size: 13px;
        color: #8e8f90;
      }
    }
  }

  .van-nav-bar {
    background-color: #f8f8f9;
  }
}
</style>